package cn.goour.web.sys.service

import cn.goour.web.base.entity.PageInfo
import cn.goour.web.sys.entity.User
import cn.goour.web.sys.repository.UserRepository
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import javax.annotation.PostConstruct
import javax.persistence.criteria.CriteriaBuilder
import javax.persistence.criteria.CriteriaQuery
import javax.persistence.criteria.Root
import javax.transaction.Transactional

@Service
@Transactional
open class UserService {

    @Autowired private
    lateinit var userRepository: UserRepository

    open fun getList(pageInfo: PageInfo): Page<User> {
        val pageRequest = PageRequest(pageInfo.page - 1, pageInfo.size, Sort(Sort.Order(Sort.Direction.ASC, "id")))
        if (pageInfo.search.isEmpty()) {
            return userRepository.findAll(pageRequest)
        } else {
            return userRepository.findAll({ root: Root<User>, _: CriteriaQuery<*>, criteriaBuilder: CriteriaBuilder ->
                val search = pageInfo.search
                val c1 = criteriaBuilder.like(root.get("name"), "%$search%")
                criteriaBuilder.or(c1)
            }, pageRequest)
        }
    }

    open fun update(user: User) {
        userRepository.saveAndFlush(user)
    }

    open fun delete(ids: Array<Int>) {

    }

    init {
        logger.info("Initialized ${this.javaClass.simpleName}...")
    }

    @PostConstruct
    open fun post() {
        logger.info("PostConstruct ${this.javaClass.simpleName}...")
    }

    companion object {
        private val logger = LoggerFactory.getLogger(UserService::class.java)
    }
}